<?php
/**
 * 给模型用的复制商品用的
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/9/12 16:10
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Service\Util;


use App\Exceptions\ApiErrCode;
use App\Http\Controllers\ApiController;
use App\Models\Customer\Customer;
use App\Models\Panx\Category;
use App\Models\Panx\Product;
use App\Services\Product\CopyProductService;
use App\Services\Utils\Transaction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class CopyProductController extends ApiController
{
    /**
     * @param Request $request
     * @param CopyProductService $copyProductService
     *
     * @return array|\Illuminate\Http\Response
     */
    public function storeBatch(Request $request,
                               CopyProductService $copyProductService)
    {
        $ids = $request->ids ? explode(',', ($request->ids)) : [];

        $customer = (new Customer)
            ->with('categories')
            ->find($request->customer_id);
            $this->checkItemExist($customer, '客户');

        $products = (new Product)
            ->with(['brand', 'cosmeticMaterial', 'brandSeries', 'asset', 'category'])
            ->find($ids);

        $new_products = Transaction::handle(function () use ($copyProductService, $products, $customer) {
            return $copyProductService->batchToCustomer($products, $customer);
        });

        return $this->response(compact('new_products'));
    }
}